import Member from "../models/Member";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import _ from "lodash";
import upload from "../middlewares/upload";
import moment from "moment";
import { faker } from '../../app'

// 注册新用户
export const registerMember = async (req: any, res: any) => {
    console.log("注册新用户");
    console.log("req.body:", req.body);
    try {
        const {
            username,
            password,
            fullName,
            dateOfBirth,
            phoneNumber,
            level,
            isActive,
        } = req.body;

        // 检查会员是否已存在
        const existingMember = await Member.findOne({ username });
        if (existingMember) {
            return res.status(400).json({ message: "用户名已存在" });
        }

        // 加密密码
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        // 创建新用户
        const newMember = new Member({
            username,
            password: hashedPassword,
            fullName,
            dateOfBirth,
            phoneNumber: username,
            level,
            isActive,
            createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
            updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
        });

        const member = await newMember.save();

        if (member) {
            console.log("member:", member);
            const payload = {
                id: member._id,
                username: member.username,
                // 您可以在这里添加更多的有效载荷数据
            };

            const secretKey = "cgc"; // 应该在环境变量中设置
            const token = jwt.sign(payload, secretKey, { expiresIn: "12h" }); // 设置 token 过期时间

            res.status(201).json({
                status: "ok",
                message: "用户注册成功",
                token,
            });
        }
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 修改用户信息
export const updateMember = async (req: any, res: any) => {
    upload.single("image")(req, res, async (error: any) => {
        if (error) {
            console.log('修改用户信息:', error.message)
            return res.status(500).json({
                status: "false",
                message: error.message,
            });
        }

        try {
            const { _id } = req.body;
            const updateData = req.body;
            console.log('修改用户信息: ', updateData)

            // 如果有新的图片上传，则更新图片路径
            if (req.file) {
                updateData.avatar = req.file.path;
            } else {
                delete updateData.avatar;
            }

            // 如果更新了密码，需要重新加密
            if (updateData.password) {
                const salt = await bcrypt.genSalt(10);
                updateData.password = await bcrypt.hash(updateData.password, salt);
            }

            // 更新 updatedAt 字段
            updateData.updatedAt = moment().format("YYYY-MM-DD HH:mm:ss");

            const updatedMember = await Member.findByIdAndUpdate(
                _id,
                updateData,
                { new: true }
            ).select('-password');
            if (!updatedMember) {
                return res.status(404).json({
                    status: "false",
                    message: "未找到该用户",
                });
            }

            res.json({
                status: "ok",
                message: "更新用户信息成功!",
                data: updatedMember
            });
        } catch (error: any) {
            res.status(500).json({
                status: "false",
                message: error.message,
            });
        }
    });
};

// 查询用户信息
export const getMember = async (req: any, res: any) => {
    try {
        const { memberId } = req.params;
        const member = await Member.findById(memberId).select("-password");
        if (!member) {
            return res.status(404).json({ message: "未找到该用户" });
        }

        res.json({
            data: member,
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 删除用户
export const deleteMember = async (req: any, res: any) => {
    try {
        const { memberId } = req.params;
        const member = await Member.findByIdAndDelete(memberId);
        if (!member) {
            return res.status(404).json({ message: "未找到该用户" });
        }

        res.json({ message: "用户删除成功" });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 查询成员列表（支持分页）
export const getMembers = async (req: any, res: any) => {
    try {
        const page = parseInt(req.query.page) || 1; // 当前页码，默认为第一页
        const limit = parseInt(req.query.limit) || 20; // 每页数量，默认为 10
        const skip = (page - 1) * limit; // 计算需要跳过的文档数量

        // 确保 page 和 limit 是有效的数字
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({ message: "无效的查询参数" });
        }

        // 查询数据库并实现分页
        const members = await Member.find()
            .skip(skip)
            .limit(limit)
            .select("-password");
        const total = await Member.countDocuments(); // 获取总成员数

        res.json({
            total,
            page,
            limit,
            data: members,
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

// 通过账号密码登录
export const loginByPassword = async (req: any, res: any) => {
    const { username, password, validCode } = req.body;

    // 验证验证码是否正确
    if (req.session && req.session.captcha !== validCode) {
        return res.status(500).json({
            status: "false",
            message: "验证码错误",
        });
    }

    try {
        const member = await Member.findOne({ username });
        if (!member) {
            return res.status(500).json({ message: "用户不存在" });
        }

        const isMatch = await bcrypt.compare(password, member.password);
        if (!isMatch) {
            return res.status(500).json({ message: "密码错误" });
        }

        // 用户验证成功
        const payload = {
            id: member._id,
            username: member.username,
            // 您可以在这里添加更多的有效载荷数据
        };

        const secretKey = "cgc"; // 应该在环境变量中设置
        const token = jwt.sign(payload, secretKey, { expiresIn: "12h" }); // 设置 token 过期时间

        res.json({
            status: "ok",
            message: "登录成功",
            token,
            data: _.omit(member.toObject(), ["password"]),
        });
    } catch (error: any) {
        res.status(500).json({ message: error.message });
    }
};

export const generateMembers = async (req: any, res: any) => {
    const addNumber = 456
    try {
        let count = 0
        for (let i = 0; i < addNumber; i++) {
            // 生成随机香港号码
            const username = faker.phone.imei();

            // 加密密码
            const password = await bcrypt.hash('123456', 10);

            // 生成两到三个汉字的名字
            const fullName = faker.person.fullName();

            // 生成头像
            const avatar = faker.image.avatar();

            // 生成余额
            const balance = faker.number.float({ min: 0, max: 20000, precision: 0.01 })

            // 生成累计消费
            const accumulatedConsumption = faker.number.float({ min: 0, max: balance, precision: 0.01 });

            // 生成日期
            const createdAt = moment(faker.date.between({ from: '2021-12-22', to: '2023-12-22' })).format('YYYY-MM-DD HH:mm:ss');
            const updatedAt = moment(faker.date.between({ from: createdAt, to: '2023-12-22' })).format('YYYY-MM-DD HH:mm:ss');

            // 创建新的 Member 实例并加入数组
            const newMember = new Member({
                username,
                password,
                fullName,
                avatar: '',
                balance,
                frozenAmount: 0.00,
                accumulatedConsumption,
                dateOfBirth: null,
                address: {
                    street: '',
                    city: '',
                    state: '',
                    zipCode: '',
                    country: ''
                },
                phoneNumber: username,
                level: '1',
                isActive: true,
                createdAt,
                updatedAt
            })
            const member = await newMember.save()
            if (member) {
                count++
            }
        }
        console.log('count::', count)
        if (count === addNumber) {
            // 批量保存到数据库
            res.status(201).send('批量生成会员数据成功');
        }
    } catch (error: any) {
        console.log('error:', error)
        res.status(500).send('生成数据时出错: ' + error.message);
    }
}